/*
 * @Descripttion: 关键词
 * @version: v1.0
 * @Author: 薛玉峰
 * @Date: 2020-06-23 09:56:58
 * @LastEditors: 薛玉峰
 * @LastEditTime: 2020-07-03 09:40:19
 */ 
const express = require('express');
const router = express.Router();
// const puppeteer = require('puppeteer');
const fs = require('fs');
const crypto = require('crypto');

class So {
    
    isFileExists(path) {
        return new Promise((resolve, reject) => {
            // setTimeout(() => reject('woops'), 500);

            fs.exists(path, function(exists){
                if(exists){
                    resolve(true);
                }if(!exists){
                    reject(false);
                }
            })
        });
    }
    
    index (req, res) {
        
        try {
            
            let data = fs.readFileSync('data.txt', 'utf-8');
            data = eval(data);
            
            res.render("index", {
                title: "Web2pdf",
                category: '',
                page: 1,
                total: data.length,
                data: data
            });
        } catch (e) {
            console.error(e)
            res.json({status: 500, message: '服务错误!'});
        }
    }
    
    async list (req, res) {

        try {
            
            let word = req.query.word || null;
            let key = req.query.key || null;
            console.log('111')
            let data = [];
            if (key && word) {
                console.log('222')
                let _path_ = './public/pdf/'+key+'/';
                let isFile = await this.isFileExists(_path_);
                console.log('111', isFile)
                if (isFile) {
                    
                    let components = []
                    const files = fs.readdirSync(_path_)
                    files.forEach(function (item, index) {
                        let stat = fs.lstatSync(_path_ + item)
                        if (stat.isDirectory() === true) { 
                            components.push(item)
                        }
                    });
                    console.log(components);
                    // data = components;
                    
                } else {

                }
                
            } else if (!key && word) {

                
            } else {

            }
            
            // let workKey = crypto.createHash('md5').update(word).digest("hex");
            // console.log(workKey);

            res.render("list", {
                title: "Web2pdf",
                word: word,
                category: '',
                page: 1,
                total: data.length,
                data: data
            });
        } catch (e) {
            console.error(e)
            res.json({status: 500, message: '服务错误!'});
        }
    }
}

let s = new So();

router.get('/', s.index);
router.get('/list', s.list);

module.exports = router;